package cn.wen.core.compress;

import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.ImageView;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 加载本地图片
 */

public class ImageUtils {

    private static ExecutorService mPool = Executors.newScheduledThreadPool(Runtime.getRuntime().availableProcessors());
    private static Handler mHandler = new Handler(Looper.getMainLooper());

    public static void displayImage(final ImageView imageView, final String imageUrl) {
        if (imageView == null || TextUtils.isEmpty(imageUrl)) {
            return;
        }
        // 1.从缓存取
        Bitmap bitmap = ImageCache.getInstance().get(imageUrl);
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap);
            return;
        }
        imageView.setTag(imageUrl);
        imageView.setImageBitmap(null);
        mPool.execute(new Runnable() {
            @Override
            public void run() {
                CompressImage compressImage = CompressImageFactory.create(imageUrl);
                final Bitmap bitmap = compressImage.compress(imageView.getContext(), 480, 800);
                if (bitmap != null) {
                    ImageCache.getInstance().put(imageUrl, bitmap);
                    if (!imageUrl.equals(imageView.getTag())) {
                        return;
                    }
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            imageView.setImageBitmap(bitmap);
                        }
                    });
                }
            }
        });
    }
}
